package com.chagee.channel.server.service.third;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.mts20140618.Client;
import com.aliyun.mts20140618.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.chagee.channel.common.exception.BizException;
import com.chagee.channel.server.service.dto.MediaInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

/**
 * 阿里云媒体处理service
 */
@Slf4j
@Service
public class AliyunMtsService {

    @Value("${aliyun.mps.accessKeyId}")
    private String ACCESS_KEY_ID;
    @Value("${aliyun.mps.accessKeySecret}")
    private String SECRET_ACCESS_KEY;

    private Client initClient() throws Exception {
        String regionId = "cn-shanghai"; // MPS服务所在区域
        Config config = new Config();
        config.setAccessKeyId(ACCESS_KEY_ID);
        config.setAccessKeySecret(SECRET_ACCESS_KEY);
        config.setRegionId(regionId);
        return new Client(config);
    }

    /**
     * 查询媒体信息
     * @param ossUrl
     * @return
     */
    public MediaInfoDto queryMediaInfo(String ossUrl){
        //https://chagee20.oss-cn-shanghai.aliyuncs.com/chagee20/images/20240402/bwgf2-1712037765805.mp4
        //去掉协议
        ossUrl = ossUrl.replace("https://", "").replace("http://", "");
        String[] array = ossUrl.split("\\.");
        String bucket = array[0];
        String location = array[1];
        int index = ossUrl.indexOf("/");
        String object = ossUrl.substring(index + 1);

        try {
            Client client = initClient();

            SubmitMediaInfoJobRequest request = new SubmitMediaInfoJobRequest();
            JSONObject json = new JSONObject()
                    .set("Bucket", bucket)
                    .set("Location", location)
                    .set("Object", UriUtils.encode(object, "UTF-8"));
            request.setInput(json.toJSONString(0));
            SubmitMediaInfoJobResponse response = client.submitMediaInfoJobWithOptions(request, new RuntimeOptions());
            SubmitMediaInfoJobResponseBody.SubmitMediaInfoJobResponseBodyMediaInfoJobProperties properties = response.getBody().getMediaInfoJob().getProperties();
            String rotate = "90"; //默认竖屏拍摄
            try {
                rotate = properties.getStreams().getVideoStreamList().getVideoStream().get(0).getRotate();
            } catch (Exception e) {
                log.error("获取视频旋转角度失败", e);
            }
            return new MediaInfoDto(Integer.parseInt(properties.getHeight()), Integer.parseInt(properties.getWidth()), rotate);
        } catch (TeaException e) {
            log.error("查询媒体信息失败原因:", e);
            throw new BizException("查询媒体信息失败");
        } catch (Exception e) {
            log.error("查询媒体信息未知异常", e);
            throw new BizException("查询媒体信息异常");
        }
    }

    /**
     * 提交转码作业
     */
    public boolean submitJobs(SubmitJobsRequest request){
        log.info("SubmitJobsRequest:{}", JSONUtil.toJsonStr(request));
        try {
            Client client = initClient();
            // 提交转码作业
            log.info("开始执行转码");
            SubmitJobsResponse response = client.submitJobsWithOptions(request, new RuntimeOptions());
            log.info("转码任务响应：{}", JSONUtil.toJsonStr(response));
            SubmitJobsResponseBody.SubmitJobsResponseBodyJobResultListJobResultJob job = response.getBody().getJobResultList().getJobResult().get(0).getJob();
//            SubmitJobsResponse response = client.getAcsResponse(request);
            log.info("转码水印jobId: {}, state: {}", job.getJobId(), job.getState());
            return StrUtil.isNotEmpty(job.getJobId());
        } catch (TeaException e){
            log.error("发起转码失败原因:", e);
            throw new BizException("发起转码失败");
        } catch (Exception e) {
            log.error("发起转码未知异常", e);
            throw new BizException("发起转码异常");
        }
    }

    public void queryJob(String jobId){
        QueryJobListRequest queryJobListRequest = new com.aliyun.mts20140618.models.QueryJobListRequest()
                //转码作业ID
                .setJobIds(jobId);
        try {
            Client client = initClient();
            QueryJobListResponse response = client.queryJobListWithOptions(queryJobListRequest, new RuntimeOptions());
            String state = response.getBody().getJobList().getJob().get(0).getState();
            log.info("转码水印job状态: {}", state);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

}
